package dept

import (
	"context"
	"go-zero-project/common/excption"
	"go-zero-project/services/user/rpc/constans"
	"go-zero-project/services/user/rpc/internal/mapper"
	"go-zero-project/services/user/rpc/internal/mapper/bo"
	"go-zero-project/services/user/rpc/internal/mapper/entity"
	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type SaveLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeptSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveLogic {
	return &SaveLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SaveLogic) DeptSave(in *pb.DeptSaveReq) (*pb.DeptSaveResp, error) {
	// 1.query dept name exists ..
	deptMapper := mapper.NewDeptMapper()
	selectCount, err := deptMapper.SelectCount(l.svcCtx.DBEngin, bo.SysDeptBO{Name: in.Name, HasDelFlag: true,
		DelFlag: 0, NonParentId: true})
	if err != nil {
		return nil, err
	}
	if selectCount > 0 {
		return nil, excption.NewErrCode(constans.DeptExistError)
	}
	// 2.builder entity
	deptEntity := entity.SysDeptEntity{ParentId: in.ParentId, Name: in.Name, OrderNum: int(in.OrderNum)}
	saveErr := deptMapper.Save(l.svcCtx.DBEngin, &deptEntity)
	if saveErr != nil {
		return nil, saveErr
	}
	// 3.return obj
	return &pb.DeptSaveResp{DeptId: deptEntity.DeptId}, nil
}
